package com.example.geek.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.geek.R;
import com.example.geek.activity.HomeActivity;
import com.example.geek.activity.LoginActivity;
import com.example.geek.activity.WebActivity;
import com.example.geek.adapter.PostAdapter;
import com.example.geek.entity.PostEntity;
import com.example.geek.entity.PostListResponse;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PostFragment extends Fragment {

    private int categoryId;
    private String title;
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int pageNum = 1;
    private PostAdapter postAdapter;
    private List<PostEntity> datas = new ArrayList<>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    postAdapter.setDatas(datas);
                    postAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    public PostFragment() {
    }

    public static PostFragment newInstance(int categoryId) {
        PostFragment fragment = new PostFragment();
        fragment.categoryId = categoryId;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_post, container, false);
        recyclerView = v.findViewById(R.id.recyclerView);
        refreshLayout = v.findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        return v;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            recyclerView.setLayoutManager(linearLayoutManager);
            postAdapter = new PostAdapter(getActivity());
            postAdapter.setOnItemClickListener(new PostAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(Serializable obj) {
                    PostEntity postEntity = (PostEntity) obj;
                    String url = "http://47.112.180.188:8089/newsDetail?title=" + postEntity.getAuthor();
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    Intent intent = new Intent(getContext(), WebActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(postAdapter);
                }
            });
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    pageNum = 1;
                    getPostList(true);
                }
            });
            refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(RefreshLayout refreshlayout) {
                    refreshlayout.finishLoadMore(2000);
                    pageNum++;
                    getPostList(false);
                }
            });
            getPostList(true);
        }

    private void getPostList(boolean isRefresh) {
        SharedPreferences sp = getActivity().getSharedPreferences("sp_ttit", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        if (!token.isEmpty()) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("token", token);
            params.put("page", pageNum);
            params.put("limit", 7);
            params.put("categoryId", categoryId);
            OkHttpClient client = new OkHttpClient.Builder()
                    .build();
            String requestUrl = "http://47.112.180.188:8080/renren-fast/app/videolist/getListByCategoryId";
            String url = getAppendUrl(requestUrl, params);
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("token", token)
                    .get()
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure", e.getMessage());
                    if (isRefresh) {
                        refreshLayout.finishRefresh(true);
                    } else {
                        refreshLayout.finishLoadMore(true);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String result = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.equals("401")) {
                            Intent in = new Intent(getContext(), LoginActivity.class);
                            startActivity(in);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (isRefresh) {
                        refreshLayout.finishRefresh(true);
                    } else {
                        refreshLayout.finishLoadMore(true);
                    }
                    PostListResponse postListResponse = new Gson().fromJson(result, PostListResponse.class);
                    if (postListResponse != null && postListResponse.getCode() == 0) {
                        List<PostEntity> list = postListResponse.getPage().getList();
                        if (list != null && list.size() > 0) {
                            if (isRefresh) {
                                datas = list;
                            } else {
                                datas.addAll(list);
                            }
                            mHandler.sendEmptyMessage(0);
                        } else {
                            if (isRefresh) {
                                Looper.prepare();
                                Toast.makeText(getContext(), "暂无更多内容", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            } else {
                                Looper.prepare();
                                Toast.makeText(getContext(), "暂无更多内容", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        }
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (isRefresh) {
                                refreshLayout.finishRefresh(true);
                            } else {
                                refreshLayout.finishLoadMore(true);
                            }
                            PostListResponse postListResponse = new Gson().fromJson(result, PostListResponse.class);
                            if (postListResponse != null && postListResponse.getCode() == 0) {
                                List<PostEntity> list = postListResponse.getPage().getList();
                                if (list != null && list.size() > 0) {
                                    if (isRefresh) {
                                        datas = list;
                                    } else {
                                        datas.addAll(list);
                                    }
                                    postAdapter.setDatas(datas);
                                    postAdapter.notifyDataSetChanged();
                                } else {
                                    if (isRefresh) {
                                        Toast.makeText(getContext(), "暂无更多内容", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getContext(), "暂无更多内容", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        }
                    });
                }
            });
        } else {
            Intent intent = new Intent(getContext(), HomeActivity.class);
            startActivity(intent);
        }
    }

    private String getAppendUrl(String url, Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                if (buffer.toString().isEmpty()) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;
    }
}